<?php
/**
 * Description:
 *
 * @author      Eden
 * @datetime    2017/1/13 00:50
 * @copyright   WuHan HuQi Technology Co.,Ltd.
 * @url         http://cnhuqi.com
 */

use Wechat\Loader;
use Wechat\WechatExtends;

include_once FCPATH . "/application/third_party/qrcode/QRcode.php";
class User extends WX_Controller
{

    const QRCODE_TMPDIR = FCPATH . 'runtime';

    /**
     * 初始化
     * @throws Exception
     */
    public function __construct()
    {
        parent::__construct();
    }

    public function userInfo()
    {
        if (!empty($this->openId)) {

            $this->load->model('wx/user/Social_Model', 'social');
            $user = $this->social->getUserByOpenId($this->openId);
            if (empty($user)) {
                $this->outputError('用户不存在');
            }

            $userid = $user['userid'];
            $this->load->model('wx/user/User_Model', 'user');
            $userinfo = $this->user->getUserInfoById($userid);

            $user['lastIp'] = $userinfo['lastIp'];
            $user['lastTime'] = $userinfo['lastTime'];
            $user['created'] = $userinfo['created'];
            $user['score'] = $userinfo['score'];
            $user['amount'] = $userinfo['amount'];
            $user['amount_cny'] = money_format('%i', $userinfo['amount'] / 100);
            $user['amountBuy'] = $userinfo['amountBuy'];
            $user['amountBuy_format'] = $userinfo['amountBuy_format'];
            $user['amountUnLimit'] = $userinfo['amountUnLimit'];
            $user['amountUnLimit_format'] = $userinfo['amountUnLimit_format'];
            $user['amountFreeze'] = $userinfo['amountFreeze'];
            $user['amountFreeze_format'] = $userinfo['amountFreeze_format'];
            $user['amountCashout'] = $userinfo['amountCashout'];
            $user['amountCashout_format'] = $userinfo['amountCashout_format'];

            $deduct = $this->input->get('extra');
            if ($deduct == 'deduct') {
                $deduct = $this->_getDeduct();
                $user['deduct'] = intval($deduct);
                $user['deduct_format'] = money_format('%i', $deduct / 100);
            }

            $this->output($user);

        } else {
            $this->outputError('用户未登录');
        }
    }

    /**
     * @return mixed
     */
    protected function _getDeduct()
    {
        $db = clone($this->db);
        $db->where('puserid', $this->userid);
        $db->or_where('ppuserid', $this->userid);
        $db->select_sum('amount');
        $q = $db->get('user_wx_deduct_record');
        $row = $q->row_array();
        return $row['amount'];
    }

    /**
     * 获取用户概览数据
     * 钱包、积分、优惠券
     */
    public function userSummary()
    {
        if (!empty($this->openId)) {

            $this->load->model('wx/user/User_Model', 'user');
            $this->load->model('wx/Ticket_Model', 'ticket');
            $user = $this->user->getUserInfoById($this->userid);

            $this->output([
                'amount' => $user['amount'],
                'amount_format' => money_format('%i', $user['amount'] / 100),
                'score' => intval($user['score']),
                'ticket' => $this->ticket->getTicketSummaryForUser($this->userid)
            ]);

        } else {
            $this->outputError(self::NO_LOGIN);
        }
    }

    /**
     * 粉丝列表
     */
    public function fansLists()
    {
        if (!empty($this->openId)) {
            $level = $this->input->get('level');
            $level = empty($level) ? 1 : $level;
            $this->load->model('wx/user/SocialRelationShip_Model', 'relation');
            $fans = $this->relation->getFansListsByUserId($this->userid, $level);

            $getCounter = 'getFansCountByUserId_Level_' . $level;
            $total = $this->relation->$getCounter($this->userid);
            $data = [
                'lists' => !empty($fans) ? $fans : [],
                'total' => intval($total)
            ];
            $this->output($data);
        } else {
            $this->outputError('用户未登录');
        }
    }

    /**
     * 统计粉丝数量
     */
    public function fansCount()
    {
        if (!empty($this->openId)) {

            $this->load->model('wx/user/SocialRelationShip_Model', 'relation');
            $level_1 = $this->relation->getFansCountByUserId_Level_1($this->userid);
            $level_2 = $this->relation->getFansCountByUserId_Level_2($this->userid);
            $this->output([
                'level1' => intval($level_1),
                'level2' => intval($level_2)
            ]);

        } else {
            $this->outputError('用户未登录');
        }
    }

    /**
     * 海报
     */
    public function bill()
    {
        if (!empty($this->openId)) {

            $this->load->model('wx/user/User_Model', 'user');
            $profile = $this->user->getUserProfileById($this->userid);
            if (empty($profile)) {
                $this->outputError('用户信息不存在');
            }

            if (!empty($profile['bill'])) {
                $this->output(['bill' => thumb($profile['bill'])]);
            }

            $cacheKey = md5(uniqid() . microtime());
            $saveInfo = $this->user->saveQrcodeParams($cacheKey, json_encode(['puserid' => $this->userid]));
            if (!$saveInfo) {
                $this->outputError('无法生成二维码');
            }

            Loader::config($this->options);
            $wechat = Loader::get('extends');
            $qrcode = $wechat->getQRCode($cacheKey, 2);
            if (empty($qrcode['ticket'])) {
                $this->outputError('无法生成二维码');
            }
            $qrcodeUrl = $wechat->getQRUrl($qrcode['ticket']);
            if (empty($qrcodeUrl)) {
                $this->outputError('无法生成二维码');
            }

            // 引入库文件
            $this->load->model('common/Setting_Model', 'sets');
            $setting = $this->sets->getSetting('wx', 'bill');
            if (empty($setting)) {
                // 没有背景
                $this->outputError('没有背景');
            }

            // 有背景
            $background = thumb($setting['image']);
            $local = $setting['local'];
            $size = $setting['size'];

            // 将二维码与背景结合
            // 二维码图片资源
            $QRcodeImageContent = imagecreatefromstring(file_get_contents($qrcodeUrl));
            $QRcodeImageX = imagesx($QRcodeImageContent);
            $QRcodeImageY = imagesy($QRcodeImageContent);

            // 海报背景图片资源
            $sourceImageContent = imagecreatefromstring(file_get_contents($background));

            imagecopyresampled($sourceImageContent, $QRcodeImageContent, $local['x'], $local['y'], 0, 0, $size['width'],
                $size['height'], $QRcodeImageX, $QRcodeImageY);

            $url = $this->saveTmpFile($sourceImageContent);
            if (!$url) {
                $this->outputError(['生成失败']);
            }

            $this->load->model('wx/user/User_Model', 'user');
            $this->user->setBillValue($this->userid, $url);

            $this->output([
                'bill' => thumb($url),
                'qrcode' => $qrcodeUrl
            ]);
        } else {
            $this->outputError(self::NO_LOGIN);
        }
    }

    /**
     * @param $sourceImageContent
     * @return bool|string
     */
    private function saveTmpFile($sourceImageContent)
    {
        $tmpDir = self::QRCODE_TMPDIR;
        if (!is_dir($tmpDir)) {
            @mkdir($tmpDir);
        }
        if (!is_writable($tmpDir)) {
            @chmod($tmpDir, '0777');
        }

        $fileName = md5(uniqid()) . '.png';
        $fileFullPath = $tmpDir . '/' . $fileName;
        imagepng($sourceImageContent, $fileFullPath);
        $filepath = '/a/' . date('Y/m') . '/';
        $aurl = $filepath . $fileName;
        $this->load->library('core/Beansdb.php', 'beansdb');
        if (!$this->beansdb->save($aurl, file_get_contents($fileFullPath))) {
            return false;
        }
        @unlink($fileFullPath);
        return $aurl;
    }

    /**
     * 取现
     */
    public function cashout()
    {
        if (!empty($this->openId)) {



        } else {
            $this->outputError(self::NO_LOGIN);
        }
    }
}
